// ====================================================
//
// This file is part of the Cscec81 Passport Base Platform.
//
// Create by Cscec81 <support@cscec81.com>
// Copyright (c) 2020-2025 cscec81.com
//
// ====================================================

package com.cscec81.passport.base.oauth2.server.authorization.customizer;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;

import java.util.HashMap;

public class DefaultOAuth2TokenCustomizer extends AbstractTokenCustomizer implements OAuth2TokenCustomizer<JwtEncodingContext> {

  @Override
  public void customize(JwtEncodingContext context) {
    Authentication authentication = context.getPrincipal();
    if (authentication.isAuthenticated()) {
      HashMap attributes;
      JwtClaimsSet.Builder jwtClaimSetBuilder;
      if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
        if (ObjectUtils.isNotEmpty(authentication)) {
          attributes = new HashMap();
          this.appendAll(attributes, authentication, context.getAuthorizedScopes());
          jwtClaimSetBuilder = context.getClaims();
          jwtClaimSetBuilder.claims((claims) -> {
            claims.putAll(attributes);
          });
        }
      }
    }
  }
}
